"""
保单管理相关的 API 端点
"""
from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, status as status_module, Query
from ....schemas.policy import (
    PolicyResponse,
    PolicyCreate,
    PolicyUpdate,
    PolicyDetailResponse
)
from ....schemas.response import BaseResponse
from ....crud.policy import policy_crud
from ....models.user import User
from ...deps import get_current_active_user, require_admin
from datetime import date

router = APIRouter()


@router.get(
    "/",
    response_model=BaseResponse[List[PolicyDetailResponse]],
    summary="获取保单列表",
    description="获取保单列表，包含销售员信息"
)
async def get_policies(
        skip: int = Query(0, ge=0, description="跳过的记录数"),
        limit: int = Query(100, ge=1, le=100, description="返回的记录数"),
        current_user: User = Depends(get_current_active_user)  # 查看用户状态及token是否过去
):
    """获取保单列表"""
    try:
        policies = await policy_crud.get_policies_with_salesman_info(skip=skip, limit=limit)
        return BaseResponse[List[PolicyDetailResponse]](
            code=200,
            message="获取保单列表成功",
            data=[PolicyDetailResponse.model_validate(policy) for policy in policies]
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取保单列表失败: {str(e)}"
        )


@router.get(
    "/my",
    response_model=BaseResponse[List[PolicyResponse]],
    summary="获取当前用户的保单列表",
    description="获取当前登录用户作为销售员的保单列表"
)
async def get_my_policies(
        skip: int = Query(0, ge=0, description="跳过的记录数"),
        limit: int = Query(100, ge=1, le=100, description="返回的记录数"),
        current_user: User = Depends(get_current_active_user)
):
    """获取当前用户的保单列表"""
    try:
        policies = await policy_crud.get_policies_by_salesman(
            salesman_job_number=current_user.job_number,
            skip=skip,
            limit=limit
        )

        # 构造响应数据
        policy_list = []
        for policy in policies:
            policy_dict = {
                "policy_number": policy.policy_number,
                "applicant_name": policy.applicant_name,
                "insured_name": policy.insured_name,
                "insured_count": policy.insured_count,
                "insured_date": policy.insured_date,
                "start_date": policy.start_date,
                "end_date": policy.end_date,
                "premium": policy.premium,
                "occupation": policy.occupation,
                "company_id": policy.company_id,
                "product_id": policy.product_id,
                "risk_type_id": policy.risk_type_id,
                "issuance_type_id": policy.issuance_type_id,
                "file_path": policy.file_path,
                "salesman_job_number": getattr(policy, 'salesman_id', None),
                "created_at": policy.created_at,
                "updated_at": policy.updated_at,
            }
            policy_list.append(policy_dict)

        return BaseResponse[List[PolicyResponse]](
            code=200,
            message="获取我的保单列表成功",
            data=[PolicyResponse.model_validate(policy) for policy in policy_list]
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取保单列表失败: {str(e)}"
        )


@router.get(
    "/search",
    response_model=BaseResponse[List[PolicyResponse]],
    summary="搜索保单",
    description="根据条件搜索保单"
)
async def search_policies(
        applicant_name: Optional[str] = Query(None, description="投保人姓名"),
        insured_name: Optional[str] = Query(None, description="被保人姓名"),
        company_id: Optional[str] = Query(None, description="保险公司编号"),
        product_id: Optional[str] = Query(None, description="产品编号"),
        salesman_job_number: Optional[List[str]] = Query(None, description="销售员工号"),
        risk_type_id: Optional[str] = Query(None, description="风险类型编号"),
        start_date: Optional[date] = Query(None, description="保单开始日期"),
        end_date: Optional[date] = Query(None, description="保单结束日期"),
        skip: int = Query(0, ge=0, description="跳过的记录数"),
        limit: int = Query(100, ge=1, le=100, description="返回的记录数"),
        current_user: User = Depends(get_current_active_user)
):
    """搜索保单"""

    try:
        policies = await policy_crud.search_policies(
            applicant_name=applicant_name,
            insured_name=insured_name,
            company_id=company_id,
            product_id=product_id,
            salesman_job_number=salesman_job_number,
            risk_type_id=risk_type_id,
            start_date=start_date,
            end_date=end_date,
            skip=skip,
            limit=limit
        )
        # 构造响应数据
        policy_list = []
        for policy in policies:
            policy_dict = {
                "policy_number": policy.policy_number,
                "applicant_name": policy.applicant_name,
                "insured_name": policy.insured_name,
                "insured_count": policy.insured_count,
                "insured_date": policy.insured_date,
                "start_date": policy.start_date,
                "end_date": policy.end_date,
                "premium": policy.premium,
                "occupation": policy.occupation,
                "company_id": policy.company_id,
                "product_id": policy.product_id,
                "risk_type_id": policy.risk_type_id,
                "issuance_type_id": policy.issuance_type_id,
                "file_path": policy.file_path,
                "salesman_job_number": getattr(policy, 'salesman_id', None),
                "created_at": policy.created_at,
                "updated_at": policy.updated_at,
            }
            policy_list.append(policy_dict)

        return BaseResponse[List[PolicyResponse]](
            code=200,
            message="搜索保单成功",
            data=[PolicyResponse.model_validate(policy) for policy in policy_list]
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"搜索保单失败: {str(e)}"
        )


@router.get(
    "/count",
    response_model=BaseResponse[int],
    summary="统计保单数量",
    description="统计保单总数量"
)
async def count_policies(
        current_user: User = Depends(get_current_active_user)
):
    """统计保单数量"""
    try:
        count = await policy_crud.count_policies()
        return BaseResponse[int](
            code=200,
            message="统计保单数量成功",
            data=count
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"统计保单数量失败: {str(e)}"
        )


@router.get(
    "/{policy_number}",
    response_model=BaseResponse[PolicyDetailResponse],
    summary="根据保单号获取保单详情",
    description="根据保单号获取保单详细信息"
)
async def get_policy_by_number(
        policy_number: str,
        current_user: User = Depends(get_current_active_user)
):
    """根据保单号获取保单详情"""
    try:
        policy_detail = await policy_crud.get_policy_detail(policy_number)
        return BaseResponse[PolicyDetailResponse](
            code=200,
            message="获取保单详情成功",
            data=PolicyDetailResponse.model_validate(policy_detail)
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status_module.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取保单详情失败: {str(e)}"
        )


@router.post(
    "/",
    response_model=BaseResponse[PolicyResponse],
    summary="创建新保单",
    description="创建新保单"
)
async def create_policy(
        policy_data: PolicyCreate,
        current_user: User = Depends(get_current_active_user)
):
    """创建新保单"""
    try:
        policy = await policy_crud.create_policy(policy_data)

        # 构造响应数据
        policy_dict = {
            "policy_number": policy.policy_number,
            "applicant_name": policy.applicant_name,
            "insured_name": policy.insured_name,
            "insured_count": policy.insured_count,
            "insured_date": policy.insured_date,
            "start_date": policy.start_date,
            "end_date": policy.end_date,
            "premium": policy.premium,
            "occupation": policy.occupation,
            "company_id": policy.company_id,
            "product_id": policy.product_id,
            "risk_type_id": policy.risk_type_id,
            "issuance_type_id": policy.issuance_type_id,
            "file_path": policy.file_path,
            "salesman_job_number": getattr(policy, 'salesman_id', None),
            "created_at": policy.created_at,
            "updated_at": policy.updated_at,
        }

        return BaseResponse[PolicyResponse](
            code=200,
            message="创建保单成功",
            data=PolicyResponse.model_validate(policy_dict)
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status_module.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建保单失败: {str(e)}"
        )


@router.put(
    "/{policy_number}",
    response_model=BaseResponse[PolicyResponse],
    summary="更新保单信息",
    description="更新指定保单的信息"
)
async def update_policy(
        policy_number: str,
        policy_data: PolicyUpdate,
        current_user: User = Depends(get_current_active_user)
):
    """更新保单信息"""
    try:
        policy = await policy_crud.update_policy(policy_number, policy_data)

        # 构造响应数据
        policy_dict = {
            "policy_number": policy.policy_number,
            "applicant_name": policy.applicant_name,
            "insured_name": policy.insured_name,
            "insured_count": policy.insured_count,
            "insured_date": policy.insured_date,
            "start_date": policy.start_date,
            "end_date": policy.end_date,
            "premium": policy.premium,
            "occupation": policy.occupation,
            "company_id": policy.company_id,
            "product_id": policy.product_id,
            "risk_type_id": policy.risk_type_id,
            "issuance_type_id": policy.issuance_type_id,
            "file_path": policy.file_path,
            "salesman_job_number": getattr(policy, 'salesman_id', None),
            "created_at": policy.created_at,
            "updated_at": policy.updated_at,
        }

        return BaseResponse[PolicyResponse](
            code=200,
            message="更新保单成功",
            data=PolicyResponse.model_validate(policy_dict)
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status_module.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新保单失败: {str(e)}"
        )


@router.delete(
    "/{policy_number}",
    response_model=BaseResponse[str],
    summary="删除保单",
    description="删除指定的保单（需要管理员权限）"
)
async def delete_policy(
        policy_number: str,
        current_user: User = Depends(require_admin)  # 只有管理员可以删除保单
):
    """删除保单"""
    try:
        await policy_crud.delete_policy(policy_number)
        return BaseResponse[str](
            code=200,
            message="删除保单成功",
            data="保单已被成功删除"
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status_module.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status_module.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除保单失败: {str(e)}"
        )
